package br.edu.ufcg.msnlab2.grupo02.booleSimpson;

import br.edu.ufcg.msnlab2.misc.Function;
import br.edu.ufcg.msnlab2.misc.NumericalIntegrationMethod;

public class SimpsonsCompositeRule implements NumericalIntegrationMethod {

	private int numberOfIntervals;

	public SimpsonsCompositeRule() {
		this(8);
	}
	
	public SimpsonsCompositeRule( int n ) {
		setNumberOfIntervals( n );
	}

	private void setNumberOfIntervals( int intervals ) {
		this.numberOfIntervals = intervals + (intervals % 2);
	}
	
	@Override
	public double integrate( Function f, double a, double b ) {
		double h = (b-a)/numberOfIntervals;
		double ans = f.evaluate( a ) + f.evaluate( b );
		double x = a;
		int m = 4;
		for ( int i = 1; i < numberOfIntervals; i++ ) {
			x+= h;
			ans += m * f.evaluate( x );
			m = 6 - m;
		}
		return h * ans / 3;
	}

}
